package com.example.yz.happywoker;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ListDetailActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView title;
    private TextView address;
    private TextView phone;
    private TextView content;
    private TextView date;
    public Button button_list;
    private String myobject;
    private String status;
    private ImageView listdetail_back02;

    private String orderID;
    private String EmployerID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_detail);
        Intent intent = getIntent();
        myobject = intent.getStringExtra("myobject");
        Log.e("myobject", "" + myobject);
        title = (TextView) findViewById(R.id.title_list);
        address = (TextView) findViewById(R.id.address_list);
        phone = (TextView) findViewById(R.id.phone_list);
        content = (TextView) findViewById(R.id.content_list);
        date = (TextView) findViewById(R.id.date_list);
        listdetail_back02 = (ImageView) findViewById(R.id.listdetail_back);
        listdetail_back02.setOnClickListener(this);
        button_list = (Button) findViewById(R.id.button_list_Detail);
        button_list.setOnClickListener(this);
        getInfo();

    }


    private void getInfo() {
        if (isNetworkAvailable(this)) {
            AVQuery<AVObject> avQuery = new AVQuery<>("MyOrderList");
            avQuery.getInBackground(myobject, new GetCallback<AVObject>() {
                @Override
                public void done(AVObject avObject, AVException e) {
                    String str = null;
                    if (avObject.get("RepairCategory") != null) {
                        title.setText(avObject.get("RepairCategory").toString());
                    }
                    if (avObject.get("RealAddress") != null) {
                        address.setText(avObject.get("RealAddress").toString());
                    }
                    if (avObject.get("EmployerID") != null) {
                        phone.setText(avObject.get("EmployerID").toString());
                        EmployerID = avObject.get("EmployerID").toString();
                    }
                    if (avObject.get("ServiceContent") != null) {
                        content.setText(avObject.get("ServiceContent").toString());
                    }
                    if (ConverToString(avObject.getCreatedAt()) != null) {
                        date.setText(ConverToString(avObject.getCreatedAt()));
                    }
                    if (avObject.get("Status") != null) {
                        status = avObject.get("Status").toString();
                    }
                    orderID = avObject.getObjectId();
                    // object 就是 id 为 558e20cbe4b060308e3eb36c 的 Todo 对象实例
                }
            });
        } else {
            Toast.makeText(this, "当前无网络连接", Toast.LENGTH_SHORT).show();
        }
    }

    //把日期转为字符串
    public static String ConverToString(Date date) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        return df.format(date);
    }

    private boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    //      System.out.println(i + getString(R.string.netState) + networkInfo[i].getState());
                    //    System.out.println(i + getString(R.string.netType) + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.listdetail_back:
                finish();
                break;
            case R.id.button_list_Detail:
                if (status.equals("1")) {
                    if (AVUser.getCurrentUser().get("Busy") == null || AVUser.getCurrentUser().get("Busy").equals("0"))//判断工人状态
                    {
//工人创建订单，将订单ID传输到RobOrderList中，同时改变订单状态，通过定时器不断查询状态是否改变（雇主是否更改状态），如状态更改则表示抢单成功。
                        final AVObject todoFolder = new AVObject("RobMyOrderList");// 构建对象
                        todoFolder.put("OrderNumber", orderID);//设置订单号
                        orderID=null;
                        todoFolder.put("RoberName", AVUser.getCurrentUser().get("Name").toString());// 设置用户名
                        todoFolder.put("State", "1");// 设置订单状态
                        todoFolder.put("RoberId", AVUser.getCurrentUser().getObjectId());
                        todoFolder.put("robWokerPhone", AVUser.getCurrentUser().getString("username"));
//                        todoFolder.put("robBirth", AVUser.getCurrentUser().get("DateBirth").toString());
                        todoFolder.put("EmployerID", EmployerID);
                        todoFolder.saveInBackground(new SaveCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    GlobalData.IdG=null;// 保存成功之后，objectId 会自动从服务端加载到本地
                                    Toast.makeText(ListDetailActivity.this,"提交成功，等待雇主确认",Toast.LENGTH_LONG).show();
                                } else {
                                    // 失败的话，请检查网络环境以及 SDK 配置是否正确
                                }
                            }
                        });
                    } else {
                        Toast.makeText(getApplication(), "有尚未完成订单 暂时无法申请", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplication(), "无法申请", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

